package net.m510.autosurfer.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import org.jsoup.select.Elements;

public class Parameters extends HashMap<String, String> {
	private static final long serialVersionUID = 1L;

	public Parameters() {}
	
	
	public List<NameValuePair> asNameValueList() {
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for ( Map.Entry<String, String> e : super.entrySet() ) {
			list.add(new BasicNameValuePair(e.getKey(), e.getValue()));
		}
		return list;
	}

	public NameValuePair getNameValuePair(String name) {
		return new BasicNameValuePair(name, get(name));
	}

	public static Parameters create() {
		return new Parameters();
	}
	public static Parameters create(FormElement form) {
		Parameters p = new Parameters();
		// INPUTタグからパラメータ生成
		for ( Element e : form.select("input") ) {
			String name = e.attr("name");
			String type = e.attr("type");
			if ( name.length() == 0 ) continue;
			if ( "radio".equalsIgnoreCase(type) && !e.hasAttr("checked") ) continue;	// radioボタンでcheckedがないものはスキップ
			p.put(name, e.attr("value"));
		}
		
		// SELECTタグからパラメータ生成
		for ( Element e : form.select("select") ) {
			String name = e.attr("name");
			if ( name.length() == 0 ) continue;
			Elements options = e.getElementsByTag("option");
			String value = null;
			if ( options.size() == 1) {
				value = options.first().attr("value");
			} else {
				for (Element option : options) {
					if ( option.hasAttr("selected") ) {
						value = option.attr("value");
						break;
					}
				}
			}
			p.put(name, value);
		}
		return p;
	}
}
